<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- CSRF元数据 -->
    <meta name="_csrf" th:content="${_csrf.token}"/>
    <meta name="_csrf_header" th:content="${_csrf.headerName}"/>
    <meta name="_csrf_parameter" th:content="${_csrf.parameterName}"/>
    <title>仓库管理 - 哈尔滨双城区农产品物流园管理系统</title>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/datatables/1.10.21/css/dataTables.bootstrap4.min.css">
    <link rel="stylesheet" th:href="@{/css/style.css}">
    <style>
        .content-header {
            margin-bottom: 20px;
        }
        .warehouse-container {
            padding: 20px;
        }
        .action-btn {
            margin-right: 5px;
        }
        .dataTables_wrapper {
            padding: 0;
        }
        .form-group.required .control-label:after {
            content: "*";
            color: red;
        }
        .modal-footer {
            justify-content: space-between;
        }
    </style>
</head>
<body>
    <div class="warehouse-container">
        <!-- 内容头部 -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0"><i class="fas fa-warehouse mr-2"></i>仓库管理</h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="#" onclick="parent.loadContent('dashboard')">首页</a></li>
                            <li class="breadcrumb-item active">仓库管理</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <!-- 主要内容 -->
        <div class="container-fluid">
            <!-- 卡片 -->
            <div class="card">
                <div class="card-header">
                    <div class="row">
                        <div class="col-md-8">
                            <h3 class="card-title">哈尔滨双城区-仓库信息列表</h3>
                        </div>
                        <div class="col-md-4 text-right">
                            <button type="button" class="btn btn-primary" onclick="addWarehouse()">
                                <i class="fas fa-plus"></i> 添加仓库
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <!-- 搜索表单 -->
                    <div class="row mb-3">
                        <div class="col-md-12">
                            <form id="searchForm" class="form-inline">
                                <div class="form-group mb-2 mr-3">
                                    <label for="searchName" class="mr-2">仓库名称:</label>
                                    <input type="text" class="form-control" id="searchName" placeholder="输入仓库名称">
                                </div>
                                <div class="form-group mb-2 mr-3">
                                    <label for="searchType" class="mr-2">仓库类型:</label>
                                    <select class="form-control" id="searchType">
                                        <option value="">全部</option>
                                        <option value="1">常温仓</option>
                                        <option value="2">冷藏仓</option>
                                        <option value="3">冷冻仓</option>
                                        <option value="4">危险品仓</option>
                                    </select>
                                </div>
                                <div class="form-group mb-2 mr-3">
                                    <label for="searchStatus" class="mr-2">状态:</label>
                                    <select class="form-control" id="searchStatus">
                                        <option value="">全部</option>
                                        <option value="0">正常</option>
                                        <option value="1">维护中</option>
                                        <option value="2">已满</option>
                                    </select>
                                </div>
                                <button type="button" class="btn btn-primary mb-2 mr-2" onclick="searchWarehouses()">
                                    <i class="fas fa-search"></i> 搜索
                                </button>
                                <button type="button" class="btn btn-secondary mb-2" onclick="resetSearch()">
                                    <i class="fas fa-sync-alt"></i> 重置
                                </button>
                            </form>
                        </div>
                    </div>

                    <!-- 数据表格 -->
                    <div class="table-responsive">
                        <table id="warehouseTable" class="table table-bordered table-hover">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>仓库名称</th>
                                    <th>仓库编号</th>
                                    <th>仓库类型</th>
                                    <th>面积(㎡)</th>
                                    <th>容量(吨)</th>
                                    <th>地址</th>
                                    <th>状态</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- 数据将通过Ajax加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加/编辑仓库模态框 -->
    <div class="modal fade" id="warehouseModal" tabindex="-1" role="dialog" aria-labelledby="warehouseModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="warehouseModalLabel">添加仓库</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="warehouseForm">
                        <input type="hidden" id="warehouseId" name="warehouseId">
                        <div class="form-row">
                            <div class="form-group required col-md-6">
                                <label for="warehouseName" class="control-label">仓库名称:</label>
                                <input type="text" class="form-control" id="warehouseName" name="warehouseName" required>
                            </div>
                            <div class="form-group required col-md-6">
                                <label for="warehouseCode" class="control-label">仓库编号:</label>
                                <input type="text" class="form-control" id="warehouseCode" name="warehouseCode" required>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group required col-md-6">
                                <label for="warehouseType" class="control-label">仓库类型:</label>
                                <select class="form-control" id="warehouseType" name="warehouseType" required>
                                    <option value="">请选择类型</option>
                                    <option value="1">常温仓</option>
                                    <option value="2">冷藏仓</option>
                                    <option value="3">冷冻仓</option>
                                    <option value="4">危险品仓</option>
                                </select>
                            </div>
                            <div class="form-group col-md-6">
                                <label for="status">状态:</label>
                                <select class="form-control" id="status" name="status">
                                    <option value="0">正常</option>
                                    <option value="1">维护中</option>
                                    <option value="2">已满</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group required col-md-6">
                                <label for="area" class="control-label">面积(㎡):</label>
                                <input type="number" class="form-control" id="area" name="area" min="0" step="0.01" required>
                            </div>
                            <div class="form-group required col-md-6">
                                <label for="capacity" class="control-label">容量(吨):</label>
                                <input type="number" class="form-control" id="capacity" name="capacity" min="0" step="0.01" required>
                            </div>
                        </div>
                        <div class="form-group required">
                            <label for="address" class="control-label">地址:</label>
                            <input type="text" class="form-control" id="address" name="address" required>
                        </div>
                        <div class="form-group">
                            <label for="manager">负责人:</label>
                            <input type="text" class="form-control" id="manager" name="manager">
                        </div>
                        <div class="form-group">
                            <label for="phone">联系电话:</label>
                            <input type="text" class="form-control" id="phone" name="phone">
                        </div>
                        <div class="form-group">
                            <label for="remark">备注:</label>
                            <textarea class="form-control" id="remark" name="remark" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" id="deleteBtn" onclick="confirmDelete()" style="display:none;">
                        <i class="fas fa-trash-alt"></i> 删除
                    </button>
                    <div>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="saveWarehouse()">保存</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 确认删除模态框 -->
    <div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteModalLabel">确认删除</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p>确定要删除这个仓库吗？此操作不可恢复。</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" onclick="deleteWarehouse()">确认删除</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js"></script>
    <script>
        var warehouseTable = typeof warehouseTable !== 'undefined' ? warehouseTable : null;
        var editingId = typeof editingId !== 'undefined' ? editingId : null;
        var token = typeof token !== 'undefined' ? token : $("meta[name='_csrf']").attr("content");
        var header = typeof header !== 'undefined' ? header : $("meta[name='_csrf_header']").attr("content");

        $(document).ready(function() {
            // 添加CSRF令牌到所有AJAX请求
            $.ajaxSetup({
                beforeSend: function(xhr) {
                    xhr.setRequestHeader(header, token);
                }
            });

            // 移除原有的DataTables脚本标签
            $('script[src*="datatables.net"]').remove();
            
            // 加载DataTables核心库和Bootstrap 4扩展
            loadDataTables()
                .then(() => loadDataTablesBS4())
                .then(() => {
                    console.log('All DataTables scripts loaded');
                    initDataTable();
                })
                .catch(() => {
                    console.error('Failed to load DataTables scripts');
                    alert('加载DataTables库失败，请刷新页面重试');
                });
        });

        function loadDataTables() {
            return new Promise((resolve, reject) => {
                // 尝试从CDN加载
                $.getScript('https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js')
                    .done(function() {
                        console.log('DataTables core loaded from CDN');
                        resolve();
                    })
                    .fail(function() {
                        console.log('Failed to load DataTables from CDN, trying local backup');
                        // 从本地加载备份
                        $.getScript('/js/jquery.dataTables.min.js')
                            .done(function() {
                                console.log('DataTables core loaded from local backup');
                                resolve();
                            })
                            .fail(function() {
                                console.error('Failed to load DataTables from local backup');
                                reject();
                            });
                    });
            });
        }
        
        function loadDataTablesBS4() {
            return new Promise((resolve, reject) => {
                // 尝试从CDN加载
                $.getScript('https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js')
                    .done(function() {
                        console.log('DataTables BS4 loaded from CDN');
                        resolve();
                    })
                    .fail(function() {
                        console.log('Failed to load DataTables BS4 from CDN, trying local backup');
                        // 从本地加载备份
                        $.getScript('/js/dataTables.bootstrap4.min.js')
                            .done(function() {
                                console.log('DataTables BS4 loaded from local backup');
                                resolve();
                            })
                            .fail(function() {
                                console.error('Failed to load DataTables BS4 from local backup');
                                reject();
                            });
                    });
            });
        }
        
        function initDataTable() {
            // 检查DataTable是否已成功加载
            if ($.fn.dataTable && $.fn.dataTable.defaults) {
                console.log('DataTable is available, initializing...');
                // 初始化DataTable
                warehouseTable = $('#warehouseTable').DataTable({
                    "responsive": true,
                    "language": {
                        "url": '/js/datatables-chinese.json'
                    },
                    "lengthChange": true,
                    "autoWidth": false,
                    "searching": true,
                    "paging": true,
                    "info": true,
                    "columnDefs": [
                        {"orderable": false, "targets": 8} // 操作列不可排序
                    ]
                });
                
                // 加载数据
                loadWarehouseData();
            } else {
                console.error('DataTable is not available');
                setTimeout(function() {
                    console.log('Retrying DataTable initialization...');
                    initDataTable();
                }, 1000);
            }
        }

        function loadWarehouseData() {
            $.ajax({
                url: "/warehouse/list",
                type: "GET",
                dataType: "json",
                success: function(response) {
                    if (response.code === 200 && response.data) {
                        // 清空表格
                        warehouseTable.clear();
                        
                        // 添加数据
                        $.each(response.data, function(index, warehouse) {
                            // 处理状态显示
                            let statusHtml;
                            switch (warehouse.status) {
                                case "0":
                                    statusHtml = '<span class="badge badge-success">正常</span>';
                                    break;
                                case "1":
                                    statusHtml = '<span class="badge badge-warning">维护中</span>';
                                    break;
                                case "2":
                                    statusHtml = '<span class="badge badge-danger">已满</span>';
                                    break;
                                default:
                                    statusHtml = '<span class="badge badge-secondary">未知</span>';
                            }
                            
                            // 处理仓库类型显示
                            let warehouseTypeText;
                            switch (warehouse.warehouseType) {
                                case "1": warehouseTypeText = "常温仓"; break;
                                case "2": warehouseTypeText = "冷藏仓"; break;
                                case "3": warehouseTypeText = "冷冻仓"; break;
                                case "4": warehouseTypeText = "危险品仓"; break;
                                default: warehouseTypeText = "未知";
                            }
                            
                            // 处理操作按钮
                            let actionButtons = '<div class="btn-group" role="group">' +
                                '<button type="button" class="btn btn-sm btn-info action-btn" onclick="viewWarehouse(' + warehouse.warehouseId + ')">' +
                                '<i class="fas fa-eye"></i></button>' +
                                '<button type="button" class="btn btn-sm btn-primary action-btn" onclick="editWarehouse(' + warehouse.warehouseId + ')">' +
                                '<i class="fas fa-edit"></i></button>' +
                                '<button type="button" class="btn btn-sm btn-danger action-btn" onclick="showDeleteModal(' + warehouse.warehouseId + ')">' +
                                '<i class="fas fa-trash-alt"></i></button>' +
                                '</div>';
                            
                            // 添加行
                            warehouseTable.row.add([
                                warehouse.warehouseId,
                                warehouse.warehouseName,
                                warehouse.warehouseCode,
                                warehouseTypeText,
                                warehouse.area,
                                warehouse.capacity,
                                warehouse.address,
                                statusHtml,
                                actionButtons
                            ]);
                        });
                        
                        // 重绘表格
                        warehouseTable.draw();
                    } else {
                        console.error("获取仓库数据失败:", response.message || "未知错误");
                    }
                },
                error: function(xhr, status, error) {
                    console.error("AJAX请求失败:", error);
                }
            });
        }

        // 添加仓库
        function addWarehouse() {
            editingId = null;
            $('#warehouseModalLabel').text('添加仓库');
            $('#warehouseForm')[0].reset();
            $('#warehouseId').val('');
            $('#deleteBtn').hide();
            $('#warehouseModal').modal('show');
        }

        // 查看仓库详情
        function viewWarehouse(id) {
            // 获取仓库数据
            $.ajax({
                url: '/warehouse/' + id,
                type: 'GET',
                success: function(res) {
                    if (res.code === 200 && res.data) {
                        const warehouse = res.data;
                        
                        // 填充表单
                        $('#warehouseId').val(warehouse.warehouseId);
                        $('#warehouseName').val(warehouse.warehouseName);
                        $('#warehouseCode').val(warehouse.warehouseCode);
                        $('#warehouseType').val(warehouse.warehouseType);
                        $('#status').val(warehouse.status);
                        $('#area').val(warehouse.area);
                        $('#capacity').val(warehouse.capacity);
                        $('#address').val(warehouse.address);
                        $('#manager').val(warehouse.manager);
                        $('#phone').val(warehouse.phone);
                        $('#remark').val(warehouse.remark);
                        
                        // 设置字段为只读
                        $('#warehouseForm input, #warehouseForm select, #warehouseForm textarea').prop('disabled', true);
                        
                        // 设置模态框标题和显示
                        $('#warehouseModalLabel').text('查看仓库详情');
                        $('#deleteBtn').hide();
                        
                        // 隐藏保存按钮，修改关闭按钮文本
                        $('.modal-footer .btn-primary').hide();
                        $('.modal-footer .btn-secondary').text('关闭');
                        
                        $('#warehouseModal').modal('show');
                    } else {
                        alert('获取仓库信息失败: ' + (res.msg || '未知错误'));
                    }
                },
                error: function(xhr) {
                    alert('获取仓库信息错误: ' + xhr.statusText);
                }
            });
        }

        // 编辑仓库
        function editWarehouse(id) {
            editingId = id;
            
            // 重置表单状态
            $('#warehouseForm')[0].reset();
            $('#warehouseForm input, #warehouseForm select, #warehouseForm textarea').prop('disabled', false);
            $('.modal-footer .btn-primary').show().text('保存');
            $('.modal-footer .btn-secondary').text('取消');
            
            // 获取仓库数据
            $.ajax({
                url: '/warehouse/' + id,
                type: 'GET',
                success: function(res) {
                    if (res.code === 200 && res.data) {
                        const warehouse = res.data;
                        
                        // 填充表单
                        $('#warehouseId').val(warehouse.warehouseId);
                        $('#warehouseName').val(warehouse.warehouseName);
                        $('#warehouseCode').val(warehouse.warehouseCode);
                        $('#warehouseType').val(warehouse.warehouseType);
                        $('#status').val(warehouse.status);
                        $('#area').val(warehouse.area);
                        $('#capacity').val(warehouse.capacity);
                        $('#address').val(warehouse.address);
                        $('#manager').val(warehouse.manager);
                        $('#phone').val(warehouse.phone);
                        $('#remark').val(warehouse.remark);
                        
                        // 设置模态框标题和显示
                        $('#warehouseModalLabel').text('编辑仓库');
                        $('#deleteBtn').show();
                        $('#warehouseModal').modal('show');
                    } else {
                        alert('获取仓库信息失败: ' + (res.msg || '未知错误'));
                    }
                },
                error: function(xhr) {
                    alert('获取仓库信息错误: ' + xhr.statusText);
                }
            });
        }

        // 保存仓库信息
        function saveWarehouse() {
            // 表单验证
            if (!$('#warehouseForm')[0].checkValidity()) {
                $('#warehouseForm')[0].reportValidity();
                return;
            }
            
            // 收集表单数据
            const formData = {
                warehouseId: $('#warehouseId').val(),
                warehouseName: $('#warehouseName').val(),
                warehouseCode: $('#warehouseCode').val(),
                warehouseType: $('#warehouseType').val(),
                status: $('#status').val(),
                area: $('#area').val(),
                capacity: $('#capacity').val(),
                address: $('#address').val(),
                manager: $('#manager').val(),
                phone: $('#phone').val(),
                remark: $('#remark').val()
            };
            
            // 确定是新增还是更新
            const isNew = !formData.warehouseId;
            const url = isNew ? '/warehouse' : '/warehouse/' + formData.warehouseId;
            const method = isNew ? 'POST' : 'PUT';
            
            // 发送请求
            $.ajax({
                url: url,
                type: method,
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(res) {
                    if (res.code === 200) {
                        $('#warehouseModal').modal('hide');
                        warehouseTable.ajax.reload();
                        alert(isNew ? '添加仓库成功！' : '更新仓库成功！');
                    } else {
                        alert(isNew ? '添加仓库失败: ' : '更新仓库失败: ' + (res.msg || '未知错误'));
                    }
                },
                error: function(xhr) {
                    alert(isNew ? '添加仓库错误: ' : '更新仓库错误: ' + xhr.statusText);
                }
            });
        }

        // 显示删除确认对话框
        function showDeleteModal(id) {
            editingId = id;
            $('#deleteModal').modal('show');
        }

        // 从编辑模态框中删除
        function confirmDelete() {
            if (editingId) {
                $('#warehouseModal').modal('hide');
                setTimeout(() => {
                    $('#deleteModal').modal('show');
                }, 500);
            }
        }

        // 删除仓库
        function deleteWarehouse() {
            if (editingId) {
                $.ajax({
                    url: '/warehouse/' + editingId,
                    type: 'DELETE',
                    success: function(res) {
                        $('#deleteModal').modal('hide');
                        if (res.code === 200) {
                            warehouseTable.ajax.reload();
                            alert('删除仓库成功！');
                        } else {
                            alert('删除仓库失败: ' + (res.msg || '未知错误'));
                        }
                    },
                    error: function(xhr) {
                        $('#deleteModal').modal('hide');
                        alert('删除仓库错误: ' + xhr.statusText);
                    }
                });
            }
        }

        // 搜索仓库
        function searchWarehouses() {
            const params = {
                warehouseName: $('#searchName').val(),
                warehouseType: $('#searchType').val(),
                status: $('#searchStatus').val()
            };
            
            // 重新加载表格数据
            warehouseTable.ajax.url('/warehouse/list?' + $.param(params)).load();
        }

        // 重置搜索
        function resetSearch() {
            $('#searchForm')[0].reset();
            warehouseTable.ajax.url('/warehouse/list').load();
        }

        // 模态框关闭时重置状态
        $('#warehouseModal').on('hidden.bs.modal', function () {
            $('#warehouseForm')[0].reset();
            $('#warehouseForm input, #warehouseForm select, #warehouseForm textarea').prop('disabled', false);
            $('.modal-footer .btn-primary').show();
            $('.modal-footer .btn-secondary').text('取消');
        });
    </script>
</body>
</html> 